package 协议;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UdpServer {
    DatagramSocket socket=null;

    public UdpServer(int port) throws SocketException {
        this.socket =new DatagramSocket(port);
    }
    public void start() throws IOException {
        System.out.println("服务器上线");
        while (true){
            DatagramPacket packet=new DatagramPacket(new byte[4096],4096);
            socket.receive(packet);
            String request=new String(packet.getData(),0,packet.getLength());
            String response=process(request);
            DatagramPacket responsePacket=new DatagramPacket(response.getBytes(),response.getBytes().length
                                                            ,packet.getSocketAddress());
            socket.send(responsePacket);
            String log=String.format("[%s %d] req:%s ,resp:%s",packet.getAddress().toString(),packet.getPort()
                                                                ,request,response);
            System.out.println(log);
        }
    }

    private String process(String request) {
        String[]num=request.split(";");
        if(num.length!=3){
            String s="输入格式不对";
            return s;
        }
        int a=Integer.parseInt(num[0]);
        int b=Integer.parseInt(num[1]);
        int result=0;
        if(num[2].equals("+")){
            result= a+b;
        }else if(num[2].equals("-")){
            result=a-b;
        }else if(num[2].equals("*")){
            result=a*b;
        }else if(num[2].equals("/")){
            result=a/b;
        }else {
            System.out.println("输入格式不对");
        }
        return result+"";
    }

    public static void main(String[] args) throws IOException {
        UdpServer udpServer=new UdpServer(9090);
        udpServer.start();
    }
}
